import React, { createContext, useState } from 'react';
import { useBoolean, useRequest } from 'ahooks';
import { PageLoading } from '@ant-design/pro-layout';
import { Modal, Card, message } from 'antd';
import { ke } from '@/plugins/ke';
import EditModal from './form';
import style from './style.module.less';
import 'antd/lib/table/style/index.css';
import {
  apiDeleteArticleCategory,
  apiGetArticleCategories,
} from '@/api/article.api';

export interface Category {
  id: number;
  pid?: number;
  name: string;
  sort?: number;
  children?: this[];
}

export default () => {
  const editContext = createContext({});
  const [initialize, setInitialize] = useBoolean(false);
  const [editModalState, setEditModalState] = useState<any>({
    visible: false,
  });
  const [treeData, setTreeData] = useState<Category[]>([]);

  // 更新树数据
  const updateTreeData = (list: any[]) => {
    setTreeData(ke.array().tree(list, 'id', 'pid'));
  };

  // 修改列表行
  const updateListRow = (newData: Category) => {
    const list: any[] = [...data?.list];
    const idx = list.findIndex(_ => _.id === newData.id);
    if (idx > -1) {
      list.splice(idx, 1, newData);
    } else {
      list.push(newData);
    }
    setEditModalState({
      ...editModalState,
      data: undefined,
      visible: false,
    });

    updateTreeData(list);
  };

  // 获取列表数据
  const { data } = useRequest(apiGetArticleCategories, {
    onSuccess: () => {
      console.log('data', data?.list);
      updateTreeData(data?.list);
      setInitialize.setTrue();
    },
  });

  // 编辑
  const onOpenEditModal = async (detail?: Category) => {
    setEditModalState({
      ...editModalState,
      data: detail,
      visible: true,
    });
  };

  // 删除
  const onDeleteRow = async (detail: Category) => {
    Modal.confirm({
      title: '提醒',
      content: '确定要删除此分类?',
      onOk() {
        const hideLoading = message.loading('删除中', 0);

        apiDeleteArticleCategory([detail.id as number])
          .finally(hideLoading)
          .then((result: any) => {
            if (result.status) {
              const idx = data?.list.findIndex((_: any) => _.id === detail.id);
              if (idx > -1) {
                data?.list.splice(idx, 1);
              }
              updateTreeData(data?.list);
              message.success('删除成功');
            }
          });
      },
    });
  };

  // 添加
  const addRow = (lv: number, pid: number = 0) => {
    const obj: any = { pid, sort: ke.getTimestamp() };

    return (
      <tr className={'ant-table-cell'} key={`add-${lv}`}>
        <td colSpan={7}>
          <span style={{ paddingLeft: lv * 30 }}>
            <a className={style.link} onClick={() => onOpenEditModal(obj)}>
              添加{lv ? '子' : ''}分类
            </a>
          </span>
        </td>
      </tr>
    );
  };

  // 表格渲染
  const tableRender = (data: Category[], lv: number) => {
    return data.map(item => {
      let children: any[] = [
        <tr key={item.id} className={'ant-table-row'}>
          <td className={'ant-table-cell'}>
            <span style={{ paddingLeft: lv * 30 }}>{item.name}</span>
          </td>
          <td className={'ant-table-cell hidden-xs'}>{item.sort}</td>
          <td className={'ant-table-cell'} style={{ textAlign: 'center' }}>
            <a className={style.link} onClick={() => onOpenEditModal(item)}>
              编辑
            </a>
            <a className={style.link} onClick={() => onDeleteRow(item)}>
              删除
            </a>
          </td>
        </tr>,
      ];
      if (item.children && item.children.length) {
        children = [...children, ...tableRender(item.children, lv + 1)];
      }
      children.push(addRow(lv + 1, item.id));
      return children;
    });
  };

  return !initialize ? (
    <PageLoading />
  ) : (
    <Card>
      <editContext.Provider
        value={{
          state: editModalState,
          setState: setEditModalState,
        }}
      >
        <EditModal context={editContext} updateListRow={updateListRow} />
      </editContext.Provider>

      <div className={'ant-table ant-table-middle'}>
        <div className={'ant-table-container'}>
          <div className={'ant-table-content'}>
            <table>
              <thead className={'ant-table-thead'}>
                <tr>
                  <th className={'ant-table-cell'}>名称</th>
                  <th
                    className={'ant-table-cell hidden-xs'}
                    style={{ width: '140px' }}
                  >
                    显示顺序
                  </th>
                  <th
                    className={'ant-table-cell'}
                    style={{ textAlign: 'center', width: '140px' }}
                  >
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className={'ant-table-tbody'}>
                {tableRender(treeData, 0)}
                {addRow(0)}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </Card>
  );
};
